/**
 * Copyright (c) 2021 ZhangXiaoqiu
 * LoadingViewJs is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
import {LVImgController} from '../../component/LVImg/LVImgController.js'
import {CanvasRotateUtil} from '../../component/base/CanvasRotateUtil.js'

export default {
    props: {
        controller: {
            default: new LVImgController()
        }
    },
    data: {
        compWidth: 0,
        compHeight: 0,
        minWidth: 0,
        padding: 0,
        imgsrc: '/common/images/loading_black.png',
        canvasRotateUtil: null
    },
    onAttached() {
        if (this.controller.getPadding() != -1) {
            this.padding = this.controller.getPadding()
        } else {
            this.padding = this.minWidth / 6
        }
        if (this.controller.getImgPath() != '') {
            this.imgsrc = this.controller.getImgPath()
        }
    },
    onPageShow() {
        this.compWidth = parseInt(this.$refs.stack_id.getBoundingClientRect().width)
        this.compHeight = parseInt(this.$refs.stack_id.getBoundingClientRect().height)
        this.minWidth = Math.min(this.compWidth, this.compHeight)
        if (this.canvasRotateUtil == null) {
            // 初始化画布旋转工具类
            this.canvasRotateUtil = new CanvasRotateUtil(this.compWidth, this.compHeight)
        }
        this.onDraw()
    },
    onDraw() {
        // 获取画布控件
        const ctx = this.$refs.canvas.getContext('2d', {
            antialias: true
        })

        // 通过工具类让画布绕中心点旋转
        this.canvasRotateUtil.rotate(ctx, this.controller.getStartAngle())

        // 忽略上一次的绘制结果，只显示下面绘制的内容
        ctx.globalCompositeOperation = 'copy';
        this.drawImage(ctx)
    },
    drawImage(ctx) {
        var img = new Image();
        img.src = this.imgsrc;
        ctx.drawImage(img, (this.compWidth - this.minWidth) / 2 + this.padding, (this.compHeight - this.minWidth) / 2 + this.padding,
            this.minWidth - this.padding * 2, this.minWidth - this.padding * 2);
    },
    startAnim() {
        this.controller.startViewAnim(1500, this.onDraw)
    },
    startAnimWithTime(time) {
        this.controller.startViewAnim(time, this.onDraw)
    },
    stopAnim() {
        this.controller.stopViewAnim(this.onDraw)
    },
}
